<template>
  <div>
    <HomeHeader />
    <van-tabs v-model="activeIndex" sticky swipeable>
      <van-tab
        :title="category.name"
        v-for="category in categoryList"
        :key="category.id"
      >
        <van-list
          v-model="category.loading"
          :finished="category.finished"
          :immediate-check="false"
          finished-text="我是有底线的"
          @load="loadMorePost"
        >
          <PostItem
            :postData="post"
            v-for="post in category.postList"
            :key="post.id"
          />
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import HomeHeader from "../components/HomeHeader";
import PostItem from "../components/PostItem";
export default {
  data() {
    return {
      activeIndex: 0,
      categoryList: [],
    };
  },
  components: {
    HomeHeader,
    PostItem,
  },
  computed: {
    curCate() {
      return this.categoryList[this.activeIndex];
    },
  },
  watch: {
    activeIndex() {
      // 如果点击的是最后一个分类加号,就不加载数据而是跳转页面
      if (this.activeIndex == this.categoryList.length - 1) {
        this.$router.push("/category");
      } else {
        // 这个判断是防止加载过的分类重新加载
        if (this.curCate.postList.length == 0) {
          this.loadPost();
        }
      }
    },
  },
  created() {
    this.$axios({
      url: "/category",
    }).then((res) => {
      this.categoryList = res.data.data.map((category) => {
        return {
          ...category,
          postList: [],
          pageSize: 5,
          pageIndex: 1,
          loading: false,
          finished: false,
        };
      });
      this.categoryList.push({ name: "+" });
      this.loadPost();
    });
  },
  methods: {
    loadMorePost() {
      this.curCate.pageIndex += 1;
      this.loadPost();
    },
    loadPost() {
      this.$axios({
        url: "/post",
        params: {
          category: this.curCate.id,
          pageSize: this.curCate.pageSize,
          pageIndex: this.curCate.pageIndex,
        },
      }).then((res) => {
        this.curCate.postList = [...this.curCate.postList, ...res.data.data];
        this.curCate.loading = false;
        if (res.data.data.length < this.curCate.pageSize) {
          this.curCate.finished = true;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .van-tab:nth-last-child(2) {
  z-index: 999;
  background-color: #fff;
  position: sticky;
  right: -8px;
  line-height: 44px;
  width: 44px;
  font-size: 18 / 360 * 100vw;
  font-weight: 700;
}
</style>
